<template>
  <div class="bibi-deal theme-bg">
    <!-- 币币交易上面部分 -->
    <div class="deal flex js-sp mb-24 deal_width">
      <!-- 右侧盘口实时成交数据 -->
      <div class="handicap quotebg radius-8">
        <div
          class="hand-tabbox mb-24 flex js-st align-center point text-bold quotet3 text-14 quoteline"
        >
          <div class="hand-tab color_42">
            {{ $t("deal.handicap") }}
          </div>
        </div>
        <div class="flex js-sp family-d text-bolder text-10 quotet3 mb-11">
          <div class="w-80 text-left flex-shrink-0">
            <div>
              {{ $t("exchange.direction") }}
            </div>
          </div>
          <div class="flex-grow-1">
            <div>{{ $t("exchange.price") }}</div>
            <!-- <div>({{ gettrading?.stock_currency_name }})</div> -->
          </div>
          <div class="text-right flex-grow-1">
            <div>
              {{ $t("assets.amount") }}
            </div>
            <!-- <div>({{ gettrading?.currency_name }})</div> -->
          </div>
        </div>
        <div>
          <!-- 盘口数据 -->
          <Handicap
            class="mb-24"
            :time="state.handCap.time"
            :nowprice="state.nowprice"
            :selllist="state.handCap.sell_trade_list"
            :buylist="state.handCap.buy_trade_list"
          />
          <div
            class="hand-tabbox mb-24 flex js-st align-center point text-bold quotet3 text-14 quoteline"
          >
            <div class="hand-tab color_42">
              {{ $t("deal.realtime") }}
            </div>
          </div>
          <div class="flex js-sp family-d text-bolder text-10 quotet3 mb-11">
            <div class="w-80 text-left flex-shrink-0">
              <div>
                {{ $t("assets.time") }}
              </div>
            </div>
            <div class="flex-grow-1">
              <div>{{ $t("exchange.price") }}</div>
              <!-- <div>({{ gettrading?.stock_currency_name }})</div> -->
            </div>
            <div class="text-right flex-grow-1">
              <div>
                {{ $t("deal.volume") }}
              </div>
            </div>
          </div>
          <!-- 实时数据 -->
          <Realtime
            :deallist="state.handCap?.stock_deal_list || []"
            :time="state.handCap?.time"
          />
        </div>
      </div>
      <!-- k线中间行情 -->
      <div class="deal-center radius-8 quotebg">
        <!-- 当前股票数据 -->
        <div class="p-center mb-24">
          <div class="trad-data flex js-sp align-center">
            <div class="flex js-st align-center">
              <div class="quotet1 text-bolder text-26 family-d">
                {{ gettrading?.stock_name }}/{{ gettrading?.stock_code }}
              </div>
              <div class="tradata-right">
                <ul class="flex js-sp header-ul">
                  <li class="family-d first-price">
                    <div
                      class="text-18 mb-2 text-bolder"
                      :class="
                        state.nowData.increase_value > 0
                          ? 'text-red'
                          : 'text-green'
                      "
                    >
                      {{ $currency(state.nowData.now_price) }}
                    </div>
                    <div class="quotet3 text-10">
                      ≈{{ $currency(state.nowData.now_price) }}
                    </div>
                  </li>
                  <li>
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.increase") }}
                    </div>
                    <div
                      class="text-14 family-d text-bolder"
                      :class="
                        state.nowData.increase_value > 0
                          ? 'text-red'
                          : 'text-green'
                      "
                    >
                      {{
                        state.nowData.increase_value
                          ? (state.nowData.increase_value * 100).toFixed(2)
                          : 0
                      }}%
                    </div>
                  </li>
                  <li>
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.highest") }}
                    </div>
                    <div class="quotet2 text-14 family-d text-bolder">
                      {{ $currency(state.nowData.high_price) }}
                    </div>
                  </li>
                  <li>
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("deal.lowest") }}
                    </div>
                    <div class="quotet2 text-14 family-d text-bolder">
                      {{ $currency(state.nowData.low_price) }}
                    </div>
                  </li>
                  <li>
                    <div class="quotet3 text-10 mb-4">
                      {{ $t("exchange.24HTransactionVolume") }}
                    </div>
                    <div class="quotet2 text-14 family-d text-bolder">
                      {{
                        $currency(
                          decimalDigitsInputFilter(
                            state.nowData.transaction_amount,
                            0
                          )
                        )
                      }}{{ gettrading?.currency_name }}
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div class="flex align-center js-ed">
              <div class="text-bolder text-10 text-login status-tag">
                {{
                  state.isRestDateStatus
                    ? $t("stock.Closed")
                    : $t("stock.Opening")
                }}
              </div>
              <div class="ml-24">
                <el-switch
                  v-model="state.themeType"
                  active-color="#333333"
                  inactive-color="#F8F8F8"
                  :class="state.themeType ? 'active_img' : 'inactive_img'"
                  @change="changeTheme"
                ></el-switch>
              </div>
            </div>
          </div>
          <!-- k线行情 -->
          <div class="kline radius-8">
            <!-- <kline-charts :data="state.klineData"></kline-charts> -->
            <s-tradingview
              v-if="$store.state.exchange.stock_data?.id"
              :klineData="state.klineData"
              :is_MACD="false"
              :pageType="1"
              :decimal="Math.pow(10, gettrading?.stock_currency_accuracy)"
              class="tradingviewView"
            />
          </div>
        </div>
        <!-- 买入卖出交易 -->
        <Transaction
          ref="transaction"
          @refreshParent="refreshChild"
          :nowprice="state.nowData.now_price"
          :isRoke="state.isRoke"
          :isRestDate="state.isRestDateStatus"
          @changeRoke="changeRoke"
          @isRestDateFun="isRestDate"
        />
      </div>
      <!-- 股票 -->
      <div class="deal-box flex js-sp">
        <Dealtrading
          @tradingNowData="tradingNowData"
          :type="1"
          ref="DealTrading"
        />
      </div>
    </div>
    <!-- 下面表格 -->
    <div class="data-table quotebg radius-8 deal_width">
      <div
        class="table-tabbox flex js-st align-center point text-bold quotet3 text-14 pb-24"
      >
        <div
          class="table-tab"
          @click="changeTable(1)"
          :class="{ 'tabactive text-bolder quotet2': acTable === 1 }"
        >
          {{ $t("stock.Position") }}
        </div>
        <div
          class="table-tab"
          @click="changeTable(2)"
          :class="{ 'tabactive text-bolder quotet2': acTable === 2 }"
        >
          {{ $t("global.currentCommission") }}
        </div>
        <div
          class="table-tab"
          @click="changeTable(3)"
          :class="{ 'tabactive text-bolder quotet2': acTable === 3 }"
        >
          {{ $t("lever.transRecord") }}
        </div>
      </div>
      <div class="table-block">
        <!-- 持仓 -->
        <ContractPositon
          :nowprice="state.nowprice"
          :tradingid="gettrading?.id"
          :priceAccuracy="gettrading.stock_currency_accuracy"
          @curenttotal="curentTotal"
          ref="curentCom"
          v-show="acTable === 1"
        />
        <!-- 当前委托 -->
        <OrderRecord
          :nowprice="state.nowprice"
          :tradingid="gettrading?.id"
          ref="hisCom"
          v-show="acTable === 2"
        />
        <!-- 交易记录 -->
        <Record
          :nowprice="state.nowprice"
          :tradingid="gettrading?.id"
          :priceAccuracy="gettrading.stock_currency_accuracy"
          ref="record"
          v-show="acTable === 3"
        />
      </div>
    </div>
  </div>
</template>

<script>
import {
  computed,
  onMounted,
  reactive,
  ref,
  getCurrentInstance,
  onBeforeUnmount,
  watch,
} from "vue";
import Dealtrading from "@/components/transaction/stock/trading.vue";
import Transaction from "@/components/transaction/stock/transaction.vue";
import Handicap from "@/components/transaction/stock/handicap.vue";
import Realtime from "@/components/transaction/stock/realtime.vue";
import ContractPositon from "@/components/transaction/stock/contract-position.vue";
import OrderRecord from "@/components/transaction/stock/order-record.vue";
import Record from "@/components/transaction/stock/record.vue";
import { useStore } from "vuex";
import sTradingview from "@/components/stock-sTradingview/sTradingview.vue";
//
import { decimalDigitsInputFilter, numSort } from "@/utils/common";
import { formatDate, getTimeZoneDate, getUsTime } from "@/utils/times.js";
import { stockRobotQuotation, stockOpenTime } from "@/api/stock";
// import moment from "moment";
import UseSystemSetting from "@/commonapi/useSystemSetting";

export default {
  components: {
    Dealtrading,
    Transaction,
    Handicap,
    Realtime,
    ContractPositon,
    OrderRecord,
    Record,
    // Websocket,
    sTradingview,
  },
  setup() {
    const $store = useStore();
    const state = reactive({
      timer: null,
      klineData: null,
      ordertype: "",
      iskline: false,
      handCap: {
        sell_trade_list: [{ price: 0 }],
        buy_trade_list: [{ price: 0 }],
        stock_deal_list: [{ price: 0 }],
      }, //盘口 实时成交数据
      nowData: {}, //当前时间数据
      nowprice: 0, //当前价
      curentNum: 0, //当前委托数据量
      themeType: true,
      isRoke: false, //是否撤单
      isRestDateStatus: false, //是否休市
      openTime: {}, //开市时间对象
    });
    const themeStyle = process.env.VUE_APP_COLOR; // dark初始色调
    const curentCom = ref(null);
    const hisCom = ref(null);
    const record = ref(null);
    const transaction = ref(null);
    const {
      appContext: {
        app: {
          config: { globalProperties },
        },
      },
    } = getCurrentInstance();
    const { $websocketTool } = globalProperties;
    // 获取开关状态
    const { virtual_wallet } = UseSystemSetting();
    const gettrading = computed(() => {
      return $store.state.exchange.stock_data;
    });
    const getStockOpenTime = () => {
      stockOpenTime().then((res) => {
        state.openTime = res.data;
        isRestDate(parseInt(state.openTime?.system_time));
      });
    };
    const isRestDate = (val) => {
      let todayDate = state.openTime?.system_time;
      let hkrestList = state.openTime?.hk_rest_date;
      let usrestList = state.openTime?.us_rest_date;
      let today = getUsTime(
        parseInt(todayDate),
        "YYYY-MM-DD",
        gettrading.value?.stock_type === 2 ? "cn" : "us"
      );
      let am_close_time = parseInt(state.openTime?.am_close_time);
      let am_open_time = parseInt(state.openTime?.am_open_time);
      let pm_close_time = parseInt(state.openTime?.pm_close_time);
      let pm_open_time = parseInt(state.openTime?.pm_open_time);
      let us_close_time = parseInt(state.openTime?.us_close_time);
      let us_open_time = parseInt(state.openTime?.us_open_time);
      let isRest;
      if (gettrading.value?.stock_type === 2) {
        if (hkrestList?.length > 0) {
          isRest = hkrestList.filter((ele) => {
            let item = formatDate(getTimeZoneDate(parseInt(ele)), "yy-MM-dd");
            return item === today;
          });
        } else {
          isRest = [];
        }
      } else {
        if (usrestList?.length > 0) {
          isRest = usrestList.filter((ele) => {
            let item = formatDate(getTimeZoneDate(parseInt(ele)), "yy-MM-dd");
            return item === today;
          });
        } else {
          isRest = [];
        }
      }

      let isOpen =
        gettrading.value?.stock_type === 2
          ? (val < am_close_time && val > am_open_time) ||
            (val < pm_close_time && val > pm_open_time)
          : val < us_close_time && val > us_open_time;
      state.isRestDateStatus = isRest?.length > 0 || !isOpen;
      console.log(
        val < am_close_time && val > am_open_time,
        val < pm_close_time && val > pm_open_time,
        isOpen
      );
    };
    watch(gettrading, (newData, oldData) => {
      getStockOpenTime();
      getData(newData.id);
      closeMsg({
        socket_type: oldData?.stock_code,
        subscribed: 0,
      });
      if ($websocketTool?.ws?.readyState == 1) {
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type: newData?.stock_code,
            subscribed: 1,
          })
        );
      }
    });
   
    watch(
      () => $store.state.exchange.theme,
      (val) => {
        if (val === "night") {
          document.getElementsByTagName("body")[0].className =
            "theme-style-dark mode-style-" + themeStyle;
        } else {
          document.getElementsByTagName("body")[0].className =
            "mode-style-" + themeStyle;
        }
      }
    );
    watch(
      () => virtual_wallet.value,
      () => {
        refreshChild();
      }
    );
    const getData = (id) => {
      stockRobotQuotation(id).then((res) => {
        state.handCap.buy_trade_list = numSort(
          "desc",
          res.data.buy_trade_list,
          "price"
        );
        state.handCap.sell_trade_list = numSort(
          "desc",
          res.data.sell_trade_list,
          "price"
        );
        state.handCap.stock_deal_list = res.data.stock_deal_list;
        state.handCap.time = res.data.time;
      });
    };
    const changeRoke = () => {
      state.isRoke = !state.isRoke;
    };
    const DealTrading = ref(null);
    onMounted(() => {
      getStockOpenTime();
      if ($store.state.user.userInfo) {
        state.ordertype =
          (virtual_wallet.value ? "DEMO_" : "") +
          "USER_STOCK_ORDER_" +
          $store.state.user.userInfo.id;
      }
      //初始化样式
      state.themeType = $store.state.exchange.theme === "night" ? true : false;
      if ($store.state.exchange.theme === "night") {
        document.getElementsByTagName("body")[0].className =
          "theme-style-dark mode-style-" + themeStyle;
      } else {
        document.getElementsByTagName("body")[0].className =
          "mode-style-" + themeStyle;
      }

      state.timer = setInterval(() => {
        if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
          clearInterval(state.timer);
          state.timer = null;
          handleMsg();
        }
      }, 3000);
      document.addEventListener("visibilitychange", visibilityFn);
    });
    const visibilityFn = () => {
      // 用户息屏、或者切到后台运行 （离开页面）
      if (document.visibilityState === "hidden") {
        // closeWsMessage();
        console.log("hidden");
      }
      // 用户打开或回到页面
      console.log(document.visibilityState);
      if (document.visibilityState === "visible") {
        if ($websocketTool?.ws && $websocketTool?.ws?.readyState == 1) {
          handleMsg();
        }
      }
    };
    const handleMsg = () => {
      isRestDate(parseInt(state.openTime?.system_time));
      getData(gettrading.value?.id);
      $websocketTool?.ws.send(
        JSON.stringify({
          socket_type: gettrading.value?.stock_code,
          subscribed: 1,
        })
      );
      // $websocketTool?.ws.send(
      //   JSON.stringify({
      //     socket_type:
      //       gettrading.value?.currency_name +
      //       "/" +
      //       gettrading.value?.legal_name,
      //     subscribed: 1
      //   })
      // );
      if (state.ordertype) {
        $websocketTool?.ws.send(
          JSON.stringify({
            socket_type: state.ordertype,
            subscribed: 1,
          })
        );
      }
      $websocketTool.ws.onmessage = function(res) {
        const message = JSON.parse(res.data);
        if (message.type === gettrading.value?.stock_code) {
          if (message) {
            klineChange(message);
            onMessage(message);
          }
        }
        if (message.type === "STOCKRANKING") {
          if (DealTrading.value) {
            DealTrading.value.onMessageTrading(message);
          }
        }
        // if (
        //   message.type ===
        //   gettrading.value?.currency_name + "/" + gettrading.value?.legal_name
        // ) {

        // }
        if (state.ordertype) {
          if (message.type === state.ordertype) {
            orderChange();
          }
        }
      };
    };
    const closeMsg = (msg) => {
      if ($websocketTool?.ws && $websocketTool.ws.readyState == 1) {
        $websocketTool?.ws.send(JSON.stringify(msg));
      }
    };

    // websocket订单状态变更
    const orderChange = () => {
      refreshChild();
    };
    // 获取websocket盘口数据
    const onMessage = (val) => {
      state.handCap = val;
      isRestDate(parseInt(val.time));
    };
    // 首次进来的当前数据先用股票
    const tradingNowData = (val) => {
      if (val) {
        state.nowData = val;
        state.nowprice = val.now_price;
      }
    };
    const changeTheme = (val) => {
      state.themeType = val;
      if (val) {
        $store.commit("exchange/SET_THEME", "night");
      } else {
        $store.commit("exchange/SET_THEME", "day");
      }
    };
    const klineChange = (val) => {
      if (gettrading.value?.id === val.stock_id) {
        state.nowData = val.increase_data;
        state.nowprice = val.increase_data.now_price;
        state.klineData = val;
      }
    };
    const activeEx = ref(1);
    const acTable = ref(1);
    const exChange = (i) => {
      activeEx.value = i;
    };
    const changeTable = (i) => {
      acTable.value = i;
    };
    // 获取当前委托数据量
    const curentTotal = (val) => {
      state.curentNum = val;
    };
    const refreshChild = () => {
      setTimeout(() => {
        curentCom.value.refresh();
        hisCom.value.refresh();
        record.value.refresh();
        transaction.value.getbalance();
      }, 100);
    };
    onBeforeUnmount(() => {
      document.removeEventListener("visibilitychange", visibilityFn);
      if (state.timer) {
        clearInterval(state.timer);
        state.timer = null;
      }
      closeMsg({
        socket_type: gettrading.value?.stock_code,
        subscribed: 0,
      });
      // closeMsg({
      //   socket_type:
      //     gettrading.value.currency_name + "/" + gettrading.value.legal_name,
      //   subscribed: 0
      // });
      closeMsg({
        socket_type: state.ordertype,
        subscribed: 0,
      });
      $store.commit("exchange/SET_REDIRECT_URL", "");
    });
    return {
      state,
      exChange,
      changeTable,
      activeEx,
      acTable,
      gettrading,
      onMessage,
      klineChange,
      tradingNowData,
      orderChange,
      curentTotal,
      decimalDigitsInputFilter,
      handleMsg,
      closeMsg,
      DealTrading,
      curentCom,
      transaction,
      hisCom,
      record,
      refreshChild,
      changeTheme,
      themeStyle,
      getData,
      changeRoke,
      formatDate,
      getTimeZoneDate,
      isRestDate,
      numSort,
      getStockOpenTime,
      visibilityFn,
    };
  },
};
</script>
<style scoped lang="less">
.status-tag {
  padding: 5px 15px;
  background: rgba(229, 75, 75, 0.1);
  border: 1px solid #e54b4b;
  box-sizing: border-box;
  border-radius: 50px;
}
.bibi-deal {
  padding: 20px 0;
  box-sizing: border-box;
  padding-bottom: 60px;
}
.w-80 {
  width: 80px;
}
.deal {
  // width: 77.77%;
  margin: 0 auto;
}
.deal-box {
  width: 17.7%;
}
.deal-center {
  width: 63.55%;
  min-height: 775px;
  padding-bottom: 20px;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
.p-center {
  padding: 0 16px;
  box-sizing: border-box;
}
.trad-data {
  height: 60px;
}
.tradata-right {
  // width: 580px;
  padding-inline-end: 16px;
  margin-inline-start: 10px;
}
.mb-4 {
  margin-bottom: 4px;
}
.mb-2 {
  margin-bottom: 2px;
}
.mb-24 {
  margin-bottom: 24px;
}
.ml-24 {
  margin-inline-start: 24px;
}
.pb-24 {
  padding-bottom: 24px;
}
.mb-11 {
  margin-bottom: 11px;
}
.kline {
  width: 100%;
  height: 385px;
}
.handicap {
  width: 17.85%;
  // height: 775px;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
}
.hand-tab {
  min-height: 23px;
  margin-inline-end: 24px;
  position: relative;
  text-align: start;
}
.w-50 {
  width: 50px;
}
.data-table {
  // width: 77.77%;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.1);
  margin: 0 auto;
}
.table-tabbox {
  padding: 10px 30px 10px;
  // border-bottom: 1px solid;
}
.table-tab {
  height: 24px;
  line-height: 20px;
  position: relative;
  margin-inline-end: 24px;
  min-width: 65px;
  border-radius: 4px;
  padding: 2px 4px;
  // box-sizing: border-box;
}
.table-block {
  padding: 30px;
  padding-top: 0;
  box-sizing: border-box;
}
@media (min-width: 1301px) {
  .header-ul li {
    // min-width: 35%;
    text-align: start;
    margin-inline-end: 20px;
  }
}
@media (max-width: 1300px) {
  .header-ul li {
    // min-width: 28.5%;
    text-align: start;
    margin-inline-end: 10px;
  }
}
.first-price {
  min-width: 120px !important;
}
.active_img /deep/ .el-switch__core .el-switch__action {
  background-image: url("../../assets/images/night.png");
  background-repeat: no-repeat;
  background-size: 13px 13px;
  background-position: 1.5px 1px;
}
.inactive_img /deep/ .el-switch__core .el-switch__action {
  background-image: url("../../assets/images/day.png");
  background-repeat: no-repeat;
  background-size: 13px 13px;
  background-position: 1.5px 1px;
}
</style>
